import Vue from 'vue';
import confirm from './confirm.vue';
import { throttle } from 'lodash';

const ConfirmConstructor = Vue.extend(confirm);

const commonConfirm = function (msg = '', tip = '', btn = {}) {
  return new Promise((resolve, reject) => {
    const confirmDom = new ConfirmConstructor({
      el: document.createElement('div')
    });
    show();
    // mine-confirm组件被覆盖的属性
    confirmDom.msg = msg;
    if (typeof tip === 'string') {
      confirmDom.tip = tip;
      confirmDom.btn = btn;
    }
    if (typeof tip === 'object') {
      confirmDom.btn = tip;
    }
    confirmDom.submit = throttle(() => {
      resolve && resolve();
      close();
    }, 1000);
    confirmDom.cancel = throttle(() => {
      reject && reject();
      close();
    }, 1000);

    function close () {
      if (!confirmDom.visible) return;
      confirmDom.visible = false;
      window.setTimeout(() => {
        document.body.removeChild(confirmDom.$el);
      }, 100);
    }

    function show () {
      document.body.appendChild(confirmDom.$el);
      Vue.nextTick(() => {
        confirmDom.visible = true;
      });
    }
  })
};

export default commonConfirm;
